﻿$(document).ready(function() {
    
	// Insere o botão "Continue navegando" no ultimo passo do checkout
		
	if( $("body").hasClass("orderCompleted") ){
		$("#main").append("<a href='/' class='continueNavegando'>Continue Navegando</a>");
		Cufon.replace('#main a.continueNavegando', {
            fontFamily: 'Proxima Nova Rg'
        });	
	}
	
    if ( $('body').is('.checkout') ) {
        
        $('#main #steps #Form .submit').each(function (i) {
	
            $(this).addClass('submit' + i );
            $(this).attr({ 'id' : 'button' + i });
            
        });
       
        $('#steps').prepend(' \
            <div id="checkoutcontent"> \
                <div id="first-steps" class="clearfix"> \
                    <p>Confira o seu pedido e efetue o pagamento seguro logo abaixo:</p> \
                    <div id="informations"> \
                        <h2>Seus Dados</h2> \
                        <h3 id#="name">' + $('#infoClientFirstName').html() + " " + $('#infoClientLastName').html() + '</h3> \
                    </div> \
                    <div id="address"> \
                        <h2>Selecione o Endereço de Entrega</h2> \
                        <div id="addresslabels"> \
                            <div class="clearfix"> \
                            <a href="javascript:void(0)" id="addadressbutton">Clique Para Informar o Endere&ccedil;o</a> \
                            </div> \
                            <div class="warpit"></div> \
                        </div> \
                    </div> \
                </div> \
                <div id="registeraddress"> \
                    <h2>Cadastrar Endere&ccedil;o</h2> \
                    <div id="registerform"> \
                    </div> \
                </div>\
                <div id="cartspace"> \
                </div> \
                <div id="paymentbox"> \
                    <div id="paymentoptions" class="clearfix"> \
                        <ul> \
                            <li class="paymentoptions">Escolha a <br /> forma de pagamento:</li>\
                            <li class="creditcard"></li> \
                            <li class="paypal"></li> \
                            <li class="deposit"></li>\
                        </ul> \
                    </div> \
                    <div id="paypalpayment"> \
                        <h4 class="paypal"><a href="http://www.paypal.com" target="_blank">Paypal</a></h4> \
                        <div id="paypalbox" class="clearfix"> \
                            <div class="paypalphrase"> \
                                <p>Clique no botão abaixo para finalizar seu pedido pelo site PayPal</p>\
                            </div> \
                        </div> \
                    </div> \
                    <div id="debitopayment"> \
                        <h4 class="debito"><a href="javascript:void(0)">Débito Online</a></h4> \
                        <div id="debitobox" class="clearfix"> \
                            <div class="debitophrase"> \
                                <p>Clique no botão abaixo para finalizar seu pedido com Visa Electron</p>\
                            </div> \
                        </div> \
                    </div> \
                    <div id="credictcardform"> \
                        <h4 class="creditcard">Cartão de Crédito <span id="twocardspay"> </span></h4> \
                        <div id="creditform" class="clearfix"> \
                            <label class="titletip">Selcione a Bandeira do seu Cartão de Crédito:</label> \
                            <ul id="labels"> \
                                <li><a href="javascript:void(0)" class="visa"><span>Visa</span></a></li> \
                                <li><a href="javascript:void(0)" class="americanexpress"><span>American Express</span></a></li> \
                                <li><a href="javascript:void(0)" class="mastercard"><span>Mastercard</span></a></li> \
                                <li><a href="javascript:void(0)" class="diners"><span>Dinners Club</span></a></li> \
                            </ul> \
                            <div id="formcard" class="clearfix"> \
                                <div class="name"> \
                                    <label>Nome do Titular</label> \
                                    <p>Como está grafado no cartão)</p> \
                                    <input type="text" id="nomecard1" />\
                                </div> \
                                <div class="cardnumber"> \
                                    <label>Número <br />do Cartão</label> \
                                    <input type="text" maxlength="16" id="cardnumber1" /> \
                                </div> \
                                <div class="cardvalidate"> \
                                    <label>Data de Validade</label> \
                                </div> \
                                <div class="cardcode"> \
                                    <label>Código de <br />Segurança</label> \
                                    <input type="text" maxlength="4" id="cardcode1" /> \
                                    <a href="javascript:void(0)" class="helpcard"></a> \
                                </div> \
                                <div class="totalshpvalue"> \
                                    <label>Valor Total da Compra</label> \
                                    <input type="text" id="totalvalue1" disabled /> \
                                </div> \
                                <div class="paymenttimes"> \
                                    <label>Parcelamento</label> \
                                </div> \
                                <div class="finalizepayment"> \
                                    <a href="javascript:void(0)" id="callbuy">Finalizar a compra</a> \
                                </div> \
                            </div> \
                        </div> \
                        <div id="secondcreditcard"> \
                            <div id="secondcardcontainer"> \
                                <h4>Informe os dados do segundo cartão</h4> \
                                <div id="secondcard" class="clearfix">\
                                    <div id="labelwrap" class="clearfix"> \
                                        <!-- <div id="labelselector"> \
                                            <a href="javascript:void(0)" id="labelactive"><span>Selecione a Bandeira</span></a> \
                                            <ul> \
                                                <li>Visa</li> \
                                                <li>American Express</li> \
                                                <li>Mastercard</li> \
                                                <li>Dinners Club</li> \
                                            </ul> \
                                        </div> --> \
                                        <div class="secondlabeltitle" class="clearfix"> \
                                            <label class="titletip">Selcione a Bandeira do seu Cartão de Crédito:</label> \
                                            <ul id="labels2"> \
                                                <li><a href="javascript:void(0)" class="visa"><span>Visa</span></a></li> \
                                                <li><a href="javascript:void(0)" class="americanexpress"><span>American Express</span></a></li> \
                                                <li><a href="javascript:void(0)" class="mastercard"><span>Mastercard</span></a></li> \
                                                <li><a href="javascript:void(0)" class="diners"><span>Dinners Club</span></a></li> \
                                            </ul> \
                                        </div> \
                                    </div> \
                                    <div id="secondcartao"> \
                                        <div class="name"> \
                                            <label>Nome do Titular</label> \
                                            <p>Como está grafado no cartão)</p> \
                                            <input type="text" id="nomecard2" />\
                                        </div> \
                                        <div class="cardnumber"> \
                                            <label>Número <br />do Cartão</label> \
                                            <input type="text" maxlength="16" id="cardnumber2" /> \
                                        </div> \
                                        <div class="cardvalidate"> \
                                            <label>Data de Validade</label> \
                                        </div> \
                                        <div class="cardcode"> \
                                            <label>Código de <br />Segurança</label> \
                                            <input type="text" maxlength="4" id="cardcode2" /> \
                                            <a href="javascript:void(0)" class="helpcard"></a> \
                                        </div> \
                                        <div class="totalshpvalue"> \
                                            <label>Valor Total da Compra</label> \
                                            <input type="text" id="totalvalue2" disabled /> \
                                        </div> \
                                        <div class="paymenttimes"> \
                                            <label>Parcelamento</label> \
                                        </div> \
                                        <div class="finalizepayment"> \
                                             \
                                        </div> \
                                    </div> \
                                </div>\
                            </div> \
                             \
                        </div> \
                    </div> \
                </div> \
            </div> \
        ');
        
        Cufon.replace('#main #paymentoptions li.paymentoptions', {
            fontFamily: 'Proxima Nova Rg'
        });	
		
        //Meus dados
        
        $('#shipMoreInfo').after('<span class="about-field">(Ex.: Apto. 21 ou Conjunto 32)</span>');
        
        $('#main #steps #clientProfileCheckoutDataInfo p').has('#infoClientFirstName').remove();
        
        $('#main #steps #clientProfileCheckoutDataInfo p').each(function () {
            $(this).appendTo('#main #first-steps #informations');
            $(this).find('label').removeClass('padding');
            $(this).find('span').removeClass('padding');
        
        });
       
        $('#informations p:has("#infoClientLastName")').remove();
        
        $('#boxShipping legend').remove();
        $('#boxShipping .itemRequired').remove();
        $('#Form form:has("#boxShipping")').appendTo('#registerform');
        $('#boxShipMyAddresses .jQcustomselect li:eq(1)').trigger('click');
        $('.submit0').appendTo('#registerform');
        $('.submit0').find('span').html('Continuar');
        $('#registeraddress h2').html('Informe o endere&ccedilo para entrega');
        
        $('#shipCep').hide().before('<input type="text" id="cepreflect" />');
        $('#cepreflect').val( $('#shipCep').val()  );
        
        $('#cepreflect').live('change',function() {
         
            $('#shipCep').val( $(this).val() ) ;
            $('#shipCep').keydown();
         
        });
        
        $('#cepreflect').live('keyup',function() {
         
            $('#shipCep').val( $(this).val() ) ;
             $('#shipCep').keydown();
         
        });
        
        $('html, body').animate({
                scrollTop: $("#checkoutcontent").offset().top
        }, 800);
        $('#main #registeraddress .marginLeft').html('Informar novo endereço');
        
        $('#main #registeraddress .marginLeft').click(function() {
        
            $('#boxShipMyAddresses .jQcustomselect li:eq(0)').trigger('click');
            $('#shipCep').focus();
        
        });
        
		
        // Cart
        $('#cart h2').remove();
       // $('#cart').appendTo('#cartspace').slideDown();
       $('#cart').slideDown();
        
        
        
        $('.cardcode a').live('mouseenter',function() {
        
            $(this).append('<img class="tip" src="/Control/ArquivoExibir.aspx?NomeArquivo=tooltip_ajuda.png" />');
        
        });
        
        $('.cardcode a').live('mouseleave',function() {
        
            $(this).find('.tip').remove();
        
        });
        
        
        // Paypal buy button
        $('#paypalpayment #paypalbox').append('<a href="javascript:void(0)" id="callbuypaypal">Realizar pagamento</a>');
        
        // Paypal buy button
        $('#debitopayment #debitobox').append('<a href="javascript:void(0)" id="callbuyselection">Realizar pagamento</a>');
   
        
        $('label[for="paymentType1"]').appendTo('#paymentoptions li.creditcard');
        $('label[for="paymentType3"]').appendTo('#paymentoptions li.paypal');
        $('label[for="paymentType4"]').appendTo('#paymentoptions li.deposit');
        
        
        // Seletor do cartão 1
        $('#main #credictcardform #labels li a').click(function() {
            
            $('#main #credictcardform #labels li a').removeClass('active');
            $(this).addClass('active');
            $('#paymentCard1Brand').val( $('#paymentCard1Brand option:contains(' + $(this).find('span').html() + ')').val() );
            $('#paymentCard1Brand').trigger('change');
     
            if ( $(this).find('span:contains("America")').size() == 0 ) { 
            
                $('#cardcode1').val("").attr({"maxlength" : 3 });

            }else {
            
                $('#cardcode1').val("").attr({"maxlength" : 4 });
            
            }
              
            $('#credictcardform .jQcustomselect').remove();
            
                $('#paymentCard1ValidMonth').jQSelect({ rotulo : "Mês" , selectfirst : false });
                $('#paymentCard1ValidMonth').prev().appendTo('#formcard .cardvalidate');
                
                $('#paymentCard1ValidYear').jQSelect({ rotulo : "Ano" , selectfirst : false });
                $('#paymentCard1ValidYear').prev().appendTo('#formcard .cardvalidate');
                
                $('#Text1').jQSelect({ rotulo : "Mês" , selectfirst : false });
                $('#Text1').prev().appendTo('#secondcardcontainer .cardvalidate');
                
                $('#Text2').jQSelect({ rotulo : "Ano" , selectfirst : false });
                $('#Text2').prev().appendTo('#secondcardcontainer .cardvalidate');
            
               /* //Parcelamento
                
                // UL do parcelamento 1
                $('#paymentCard1Installments').jQSelect({ rotulo : "Parcelas" });
                $('#paymentCard1Installments').prev().appendTo('#formcard .paymenttimes');
                
                //UL do parcelamento 2
                $('#paymentCard2Installments').jQSelect({ rotulo : "Parcelas" });
                $('#paymentCard2Installments').prev().appendTo('#secondcardcontainer .paymenttimes');
                
                //Fim Parcelamento  
                */
                var intervalo = window.setTimeout(function() {
        
        
                // parcelamento 
                //Quando o ajax ficar completo se nescessário delete os items do form e coloque novamente.
                
                
                 //Remover esse comentário
                $('#formcard .paymenttimes .jQcustomselect').remove();
                
                // UL do parcelamento 1
                $('#paymentCard1Installments').jQSelect({ rotulo : "Parcelas" });
                $('#paymentCard1Installments').prev().appendTo('#formcard .paymenttimes');
                        
                //UL do parcelamento 2
                $('#secondcardcontainer .paymenttimes .jQcustomselect').remove();
                
                $('#paymentCard2Installments').jQSelect({ rotulo : "Parcelas" });
                $('#paymentCard2Installments').prev().appendTo('#secondcardcontainer .paymenttimes');
                
                
                //Fim Parcelamento
                
                },200);
                
            $('#formcard').slideDown();
            
        });
        
        // Seletor do cartão 2
        $('#main #credictcardform #labels2 li a').click(function() {
            
            $('#main #credictcardform #labels2 li a').removeClass('active');
            $(this).addClass('active');
            $('#paymentCard2Brand').val( $('#paymentCard2Brand option:contains(' + $(this).find('span').html() + ')').val() );
            $('#paymentCard2Brand').trigger('change');
            
            if ( $(this).find('span:contains("America")').size() == 0 ) { 
            
                $('#cardcode2').val("").attr({"maxlength" : 3 });

            }else {
            
                $('#cardcode2').val("").attr({"maxlength" : 4 });
            
            }
            
            
            $('#secondcardcontainer .jQcustomselect').remove();
            
            $('#Text1').jQSelect({ rotulo : "Mês", selectfirst : false });
            $('#Text1').prev().appendTo('#secondcardcontainer .cardvalidate');
            
            $('#Text2').jQSelect({ rotulo : "Ano", selectfirst : false });
            $('#Text2').prev().appendTo('#secondcardcontainer .cardvalidate');
            
            $('#secondcartao').slideDown();
            
        });
        
        $('.creditcard label').click(function() {
            $('#paypalpayment, #debitopayment').fadeOut();
            $('#credictcardform').slideDown();
            
            //pagar com 2 cards
            if ( $('#twocardspay a').size() == 0 ) {
                
                
                $('#payment2Cards a').addClass('divide').appendTo('#twocardspay');
                
            }else if ( $('#twocardspay a').size() > 0 && $('#payment2Cards a').size() > 0 ) {
                
                $('#twocardspay').empty();
                $('#payment2Cards a').addClass('divide').appendTo('#twocardspay');
            
            }
            
            $('#totalvalue1').val( $('#paymentCard1Value').val() );
            
            $('#secondcardcontainer .jQcustomselect').remove();
            
            
            $('#Text1').jQSelect({ rotulo : "Mês", selectfirst : false });
            $('#Text1').prev().appendTo('#secondcardcontainer .cardvalidate');
            
            $('#Text2').jQSelect({ rotulo : "Ano", selectfirst : false });
            $('#Text2').prev().appendTo('#secondcardcontainer .cardvalidate');
            
       
            
        });
        
        $('#paymentoptions li label').click(function() {
        
            swapdelay = window.setTimeout(function() {
                
                $('#credictcardform .jQcustomselect').remove();
            
                $('#paymentCard1ValidMonth').jQSelect({ rotulo : "Mês", selectfirst : false });
                $('#paymentCard1ValidMonth').prev().appendTo('#formcard .cardvalidate');
                
                $('#paymentCard1ValidYear').jQSelect({ rotulo : "Ano", selectfirst : false });
                $('#paymentCard1ValidYear').prev().appendTo('#formcard .cardvalidate');
                
                $('#Text1').jQSelect({ rotulo : "Mês", selectfirst : false });
                $('#Text1').prev().appendTo('#secondcardcontainer .cardvalidate');
                
                $('#Text2').jQSelect({ rotulo : "Ano", selectfirst : false });
                $('#Text2').prev().appendTo('#secondcardcontainer .cardvalidate');
            
                //Parcelamento
                
                // UL do parcelamento 1
                $('#paymentCard1Installments').jQSelect({ rotulo : "Parcelas" });
                $('#paymentCard1Installments').prev().appendTo('#formcard .paymenttimes');
                
                //UL do parcelamento 2
                $('#paymentCard2Installments').jQSelect({ rotulo : "Parcelas" });
                $('#paymentCard2Installments').prev().appendTo('#secondcardcontainer .paymenttimes');
                //Fim Parcelamento
                
                
            },600);
        
        });
        
        $('.paypal label').click(function() {
            $('#credictcardform, #debitopayment').fadeOut();
            $('#paypalpayment').slideDown();
                 
            $('#credictcardform .jQcustomselect').remove();
            
            $('#paymentCard1ValidMonth').jQSelect({ rotulo : "Mês", selectfirst : false });
            $('#paymentCard1ValidMonth').prev().appendTo('#formcard .cardvalidate');
            
            $('#paymentCard1ValidYear').jQSelect({ rotulo : "Ano", selectfirst : false });
            $('#paymentCard1ValidYear').prev().appendTo('#formcard .cardvalidate');
            
            $('#Text1').jQSelect({ rotulo : "Mês", selectfirst : false });
            $('#Text1').prev().appendTo('#secondcardcontainer .cardvalidate');
            
            $('#Text2').jQSelect({ rotulo : "Ano", selectfirst : false });
            $('#Text2').prev().appendTo('#secondcardcontainer .cardvalidate');
            
        });
        
        $('.deposit label').click(function() {
            $('#credictcardform, #paypalpayment').fadeOut();
            $('#debitopayment').slideDown();
            
            
            $('#credictcardform .jQcustomselect').remove();
            
            $('#paymentCard1ValidMonth').jQSelect({ rotulo : "Mês", selectfirst : false });
            $('#paymentCard1ValidMonth').prev().appendTo('#formcard .cardvalidate');
            
            $('#paymentCard1ValidYear').jQSelect({ rotulo : "Ano", selectfirst : false });
            $('#paymentCard1ValidYear').prev().appendTo('#formcard .cardvalidate');
            
            $('#Text1').jQSelect({ rotulo : "Mês", selectfirst : false });
            $('#Text1').prev().appendTo('#secondcardcontainer .cardvalidate');
            
            $('#Text2').jQSelect({ rotulo : "Ano", selectfirst : false });
            $('#Text2').prev().appendTo('#secondcardcontainer .cardvalidate');
            
        });
    
    
        $('#addadressbutton').live('click',function() {
            $('#registeraddress').slideDown();
            $('html, body').animate({
                scrollTop: ( $("#registeraddress").offset().top - 30 )
            }, 800);
            
            
            
        });
       
        
        $('#labelactive').live('click', function () {
            $(this).next().slideToggle();
        });
        
        $('#labelselector ul li').live('click',function() {
            $('#paymentCard2Brand').val( $('#paymentCard2Brand option:contains(' + $(this).html() + ')').val() );
            $('#paymentCard2Brand').trigger('change');
            $('#labelselector ul').fadeOut();
            $('#labelactive span').html( $(this).html() );
        });
    
       
    
        // click Selecionando endereço
        $('#button0').live('click', function () {
            
            $("#cepreflect").mask("99999-999");  
            $('#cepreflect').val( $('#shipCep').val()  );
            
            var formvalid = true;
            $('#registerform .required input').each(function () {
                if ( $(this).val() == "" ){
                    
                    formvalid = false;
                }
            });

           
            if ( formvalid ) {
            
				//$("#addresslabels > p").remove();
                $('#registeraddress').slideUp();
                $('#addresslabels h3').remove();
                $('#address').css({ 'height' : 'auto' });
                $("#informations").css({ 'height' : 'auto' });
        
                $('#addresslabels p:has(label)').remove();
                $('#Info p:not(".notification")').clone().appendTo('#addresslabels');
                $('#addresslabels .padding').removeClass();

                $('#addresslabels .warpit').appendTo('#addresslabels');
                $('#informations').height( $('#address').height() );
                
                $('#paymentoptions').slideDown();
                $('html, body').animate({
                    scrollTop: $("#paymentoptions").offset().top
                }, 800);
                $('#idfreteui').remove();
                
                
                //secondship
                /*$('#address #boxShipMyAddresses').remove();
                $("#registeraddress #registerform #boxShipMyAddresses").clone().prependTo($("#addadressbutton").parent());
                $("#address #boxShipMyAddresses label").remove();
                $('#addresslabels #shipMyAddresses').jQSelect({ rotulo : "Selecionar Endere&ccedil;o" });*/
                
                //$('#clientProfileCheckoutDataForm button').click();
                $('form:has("#boxShippingChoice")').submit();
    
                var waitforajax = window.setTimeout(function() {
                
                        $('#addresslabels p:has(label)').remove();
                        $('#Info p:not(".notification")').clone().appendTo('#addresslabels');
                        $('#addresslabels .padding').removeClass();

                        $('#addresslabels .warpit').appendTo('#addresslabels');
                    
                    $("#address .jQcustomselect").remove();
                    $('#shipMyAddresses').jQSelect({ rotulo : "Selecionar Endere&ccedil;o" });
                    $('#shipMyAddresses').parent().find('.jQcustomselect').prependTo($("#addadressbutton").parent());
                    
                    // setando tamanho das boxes
                    $('#address').css({ 'height' : 'auto' });
                    $("#informations").css({ 'height' : 'auto' });
                
                    if (  $("#address").height() > $("#informations").height() ) {
                        $("#informations").css("height", $("#address").height());
                    }else{
                        $("#address").css("height",  $("#informations").height())
                    }
                            
                },1600);
                
                $('#addresslabels #button0').hide();
                $('#addresslabels #button0').before('<button id="buttoneditaddress">Alterar Endere&ccedilo</button>');
                
            } else {
            
                $('#registeraddress').slideDown();
                $('html, body').animate({
                    scrollTop: $("#registeraddress").offset().top - 10
                }, 800);
                
                if ( $('#boxShipping #addressname').val() == "" && $('#boxShipping #addressname').next().is('.warnimage') == false  ) {
                    $('#boxShipping #addressname').after('<img src="/Control/ArquivoExibir.aspx?NomeArquivo=img_warn_addressname.png" alt="" class="warnimage" />');
                }
                
                
                if ( $('#boxShipping #shipCep').val() == "" && $('#boxShipping #shipCep').next().is('.warnimage') == false ) {
                    $('#boxShipping #shipCep').after('<img src="/Control/ArquivoExibir.aspx?NomeArquivo=img_warn_shipCep.png" alt="" class="warnimage" />');
                }
                
                if ( $('#boxShipping #shipName').val() == "" && $('#boxShipping #shipName').next().is('.warnimage') == false ) {
                    $('#boxShipping #shipName').after('<img src="/Control/ArquivoExibir.aspx?NomeArquivo=img_warn_shipName.png" alt="" class="warnimage" />');
                }
                
                if ( $('#boxShipping #shipAddress').val() == "" && $('#boxShipping #shipAddress').next().is('.warnimage') == false ) {
                   $('#boxShipping #shipAddress').after('<img src="/Control/ArquivoExibir.aspx?NomeArquivo=img_warn_shipAddress.png" alt="" class="warnimage" />');
                }
                
                if ( $('#boxShipping #shipNumber').val() == "" && $('#boxShipping #shipNumber').next().is('.warnimage') == false ) {
                    $('#boxShipping #shipNumber').after('<img src="/Control/ArquivoExibir.aspx?NomeArquivo=img_warn_shipNumber.png" alt="" class="warnimage" />');
                }
                
                if ( $('#boxShipping #shipArea').val() == "" && $('#boxShipping #shipArea').next().is('.warnimage') == false ) {
                   $('#boxShipping #shipArea').after('<img src="/Control/ArquivoExibir.aspx?NomeArquivo=img_warn_shipArea.png" alt="" class="warnimage" />');
                }
                
                if ( $('#boxShipping #shipCity').val() == "" && $('#boxShipping #shipCity').next().is('.warnimage') == false ) {
                    $('#boxShipping #shipCity').after('<img src="/Control/ArquivoExibir.aspx?NomeArquivo=img_warn_shipCity.png" alt="" class="warnimage" />');
                }
                
                if ( $('#boxShipping #shipState').val() == "" && $('#boxShipping #shipState').next().is('.warnimage') == false ) {
                   $('#boxShipping #shipState').after('<img src="/Control/ArquivoExibir.aspx?NomeArquivo=img_warn_shipState.png" alt="" class="warnimage" />');
                }
                
            }
            
            $('label[for="paymentType1"]').click();
            $('#credictcardform').hide();
            
        });
        
        
        // edit address
        $('#buttoneditaddress').live('click',function(){
            
            $("#addresslabels > p").remove();
			
            $('#paymentoptions,#paypalpayment,#debitopayment,#credictcardform').hide();
            
            $('#address .jQcustomselect .jqselectlabel').html("Selecione uma op&ccedil;&atilde;o");
            
            $('html, body').animate({
				scrollTop: $("#registeraddress").offset().top
            }, 800);
            $('#idfreteui').remove();
            $(this).remove();
            
            
            
            $('#address').css({ 'height' : 'auto' });
            $("#informations").css({ 'height' : 'auto' });
                
            if (  $("#address").height() > $("#informations").height() ) {
                $("#informations").css("height", $("#address").height());
            }else{
                $("#address").css("height",  $("#informations").height())
            }
            

        });
        
        $('#boxShipping .required input').live('change',function(){
        
            if ( $(this).next().is('.warnimage') ){
            
                $(this).next().remove();
            
            }
        
        });
        
        
        // divide
        $('#twocardspay a.divide').live('click', function() {
        
            $(this).removeClass();
            $(this).addClass('notdivide');
       
            $('#secondcardcontainer').slideDown();
            
            
            
            $('#callbuy').appendTo('#secondcard .finalizepayment');
            $('#totalvalue1').removeAttr('disabled').val( $('#paymentCard1Installments').val() );
        
            $('#totalvalue1').removeAttr('disabled').val(  $('#paymentCard1Value').val() );
            $('#totalvalue2').val(  $('#paymentCard2Value').val() );
			
			/*$('#formcard input').each(function () {
                
                if ( $(this).val() == "" ){
                    
                    if ( $(this).attr('id') == "nomecard1" ){
                        $(this).addClass('warnpinput');
                        $(this).before('<span class="warning cardnamewarn">  </span>');
                        formvalid = false;
                    }
                    
                    if ( $(this).attr('id') == "cardnumber1" ){
                        $(this).addClass('warnpinput');
                        $(this).before('<span class="warning cardnumberwarn">  </span>');
                        formvalid = false;
                    }
                    
                    if ( $(this).attr('id') == "cardcode1" ){
                        $(this).addClass('warnpinput');
                        $(this).before('<span class="warning cardcodewarn">  </span>');
                        formvalid = false;
                    }
                    
                }
                
            
            });*/
			
        });
        
        // not divide
        $('#twocardspay a.notdivide').live('click', function() {
        
     

        
            $(this).removeClass();
            $(this).addClass('divide');
            
            $('#secondcardcontainer').slideUp();
            
            $('#callbuy').appendTo('#formcard .finalizepayment');
            
            $('#totalvalue1').attr({ 'disabled' : 'disabled' }).val(  $('#paymentCard1Value').val() );
            $('#totalvalue2').val(  $('#paymentCard2Value').val() );
            
            $('#formcard input').each(function () {
                
                if ( $(this).val() == "" ){
                    
                    if ( $(this).attr('id') == "nomecard1" ){
                        $(this).before('<span class="warning cardnamewarn">  </span>');
                        formvalid = false;
                    }
                    
                    if ( $(this).attr('id') == "cardnumber1" ){
                        $(this).before('<span class="warning cardnumberwarn">  </span>');
                        formvalid = false;
                    }
                    
                    if ( $(this).attr('id') == "cardcode1" ){
                        $(this).before('<span class="warning cardcodewarn">  </span>');
                        formvalid = false;
                    }
                    
                }
                
            
            });
            
        
        });
        
        $('#credictcardform div div:has(.warning)').find('input').live('change',function() {
        
            if ( $(this).prev().is('.warning') ) {
                
               $(this).prev().fadeOut().remove();
                
            
            }
        
        });
        
       $('#credictcardform div div:has(.warning)').find('input').live('keyup',function() {
        
            if ( $(this).prev().is('.warning') ) {
                
                $(this).prev().fadeOut().remove();
            
            }
        
        });
        
        // Botão comprar
        $('#callbuy').live('click', function() {
        
            $('#credictcardform .warning').remove();
        
            var formvalid = true;
            
            if ( $('#formcard .cardvalidate .jqselectlabel:first').html() == "Mês" || $('#formcard .cardvalidate .jqselectlabel:last').html() == "Ano" ){
            
                    $('#formcard .cardvalidate').prepend('<span class="warning carddata"> </span>');
                    formvalid = false;
                }
            
            $('#formcard input').each(function () {
                
                if ( $(this).val() == "" ){
                    
                    if ( $(this).attr('id') == "nomecard1" ){
                        $(this).before('<span class="warning cardnamewarn">  </span>');
                        formvalid = false;
                    }
                    
                    if ( $(this).attr('id') == "cardnumber1" ){
                        $(this).before('<span class="warning cardnumberwarn">  </span>');
                        formvalid = false;
                    }
                    
                    if ( $(this).attr('id') == "cardcode1" ){
                        $(this).before('<span class="warning cardcodewarn">  </span>');
                        formvalid = false;
                    }
                    
                }
                
            
            });
            
            /*if ( $('#cardcode1').val().length < 4 && $('#paymentCard1Brand option:selected:contains("Express")').size() > 0 ) {
            
           
                $('#cardcode1').before('<span class="warning cardcodewarn">  </span>');
                formvalid = false;
               
            } else if ( $('#cardcode1').val().length > 3 && $('#paymentCard1Brand option:selected:contains("Express")').size() == 0 ) {
            
                $('#cardcode1').before('<span class="warning cardcodewarn">  </span>');
                formvalid = false;
                //
            }
            */
           /* if ( $('#credictcardform #labels li a.active').size() == 0 ) {
                formvalid = false;
                alert('Selecione a bandeira do seu cartão de Crédito');
               
            } */
            
            if ( $('#secondcardcontainer:visible').size() > 0 ) {
            
                if ( $('#secondcardcontainer .cardvalidate .jqselectlabel:first').html() == "Mês" || $('#secondcardcontainer .cardvalidate .jqselectlabel:last').html() == "Ano" ){
            
                    $('#secondcardcontainer .cardvalidate').prepend('<span class="warning carddata"> </span>');
                    formvalid = false;
                }
            
                $('#secondcardcontainer input').each(function () {
                
                    if ( $(this).val() == "" ){
                        
                        if ( $(this).attr('id') == "nomecard2"  ){
                            $(this).before('<span class="warning cardnamewarn">  </span>');
                            formvalid = false;
                        }
                        
                        if ( $(this).attr('id') == "cardnumber2" ){
                            $(this).before('<span class="warning cardnumberwarn">  </span>');
                            formvalid = false;
                        }
                        
                        if ( $(this).attr('id') == "cardcode2" ){
                            $(this).before('<span class="warning cardcodewarn">  </span>');
                            formvalid = false;
                        }
                        
                    }
            
                });
            
                if ( $('#cardcode2').val().length < 4 && $('#paymentCard2Brand option:selected:contains("Express")').size() > 0 ) {
            
           
                    $('#cardcode2').before('<span class="warning cardcodewarn">  </span>');
                    formvalid = false;
               
                } else if ( $('#cardcode2').val().length > 3 && $('#paymentCard2Brand option:selected:contains("Express")').size() == 0 ) {
            
                    $('#cardcode2').before('<span class="warning cardcodewarn">  </span>');
                    formvalid = false;
                    
                }
            
                /*if ( formvalid == true &&  $('#paymentCard2Brand').val() == "" ) {
                    formvalid = false;
                    alert('Selecione a bandeira do seu segundo cartão de Crédito');
                }*/
            
            }
            
            if ( formvalid ) {
                
               // $(this).after('<button>Aguarde um instante...</button>');
                $('#button1').trigger('click');
               // $(this).hide();
                
            }
            
        });
		
        // Click no botão paypal
        $('#callbuypaypal').live('click', function() {
            $('#button1').trigger('click');
            _gaq.push(['_trackPageview', 'checkout/paypal']);
            
        });
    
        // Click no botão visa Electon
        $('#callbuyselection').live('click', function() {
            $('#button1').trigger('click');
            _gaq.push(['_trackPageview', 'checkout/debitoonline']);
            
        });
        
        //####################################################################
        
        //Nome Card 1
        $('#nomecard1').live('keyUp',function() {
            $('#paymentCard1Name').val( $(this).val() );  
        });
        $('#nomecard1').live('change',function() {
            $('#paymentCard1Name').val( $(this).val() );
        });
        // Card Number 1
        $('#cardnumber1').live('keyUp',function(e) {
            $('#paymentCard1Number').val( $(this).val() );
        });

        $('#cardnumber1').live('change',function() {
            $('#paymentCard1Number').val( $(this).val() );      
        });
        // Mês 1
        $('#cardvalidatemes1').live('keyUp',function() {
            $('#paymentCard1ValidMonth').val( $(this).val() );
        });
        $('#cardvalidatemes1').live('change',function() {
            $('#paymentCard1ValidMonth').val( $(this).val() );      
        });
        // Ano 1
        $('#cardvalidatemano1').live('keyUp',function() {
            $('#paymentCard1ValidYear').val( $(this).val() );
        });
        $('#cardvalidatemano1').live('change',function() {
            $('#paymentCard1ValidYear').val( $(this).val() );      
        });
        // codigo do cartao 1
        $('#cardcode1').live('keyUp',function() {
            $('#paymentCard1Code').val( $(this).val() );
        });
        $('#cardcode1').live('change',function() {
            $('#paymentCard1Code').val( $(this).val() );      
        });
        
        // codigo do cartao ilegivel 1
        $('#ilegivel1').live('click',function() {
            $('#paymentCard1IsUnreadable').trigger('click');
        });
        
        // valor 1
        $('#totalvalue1').live('keyUp',function() {
            $('#paymentCard1Value').val( $(this).val() );
            $('#totalvalue2').val(  $('#paymentCard2Value').val() );
            $('#paymentCard1Value').trigger('change');
            $('#paymentCard1Value').trigger('keyup');
            $('#paymentCard1Value').trigger('keydown');
            
        });
        $('#totalvalue1').live('change',function() {
            $('#paymentCard1Value').val( $(this).val() );
            $('#totalvalue2').val(  $('#paymentCard2Value').val() );
            
            $('#paymentCard1Value').trigger('change');
            $('#paymentCard1Value').trigger('keyup');
            $('#paymentCard1Value').trigger('keydown');
           
        });
        
        $('#paymentCard2Value').live('change',function() {
            
            $('#totalvalue2').val(  $('#paymentCard2Value').val() );
        
        });
        
        // parcelamento 1
        $('#paymenttimes1').live('keyUp',function() {
            $('#paymentCard1Installments').val( $(this).val() );
        });
        $('#paymenttimes1').live('change',function() {
            $('#paymentCard1Installments').val( $(this).val() );      
        });
        // Valor Total 1
        $('#totalvalue1').live('keyUp',function() {
            $('#paymentCard1Value').val( $(this).val() );
        });
        $('#totalvalue1').live('change',function() {
            $('#paymentCard1Value').val( $(this).val() );      
        });
        
        
        
        //Nome Card 2
        $('#nomecard2').live('keyUp',function() {
            $('#paymentCard2Name').val( $(this).val() );  
        });
        $('#nomecard2').live('change',function() {
            $('#paymentCard2Name').val( $(this).val() );
        });
        // Card Number 2
        $('#cardnumber2').live('keyUp',function() {
            $('#paymentCard2Number').val( $(this).val() );
        });
        $('#cardnumber2').live('change',function() {
            $('#paymentCard2Number').val( $(this).val() );      
        });
        // Mês 2
        $('#cardvalidatemes2').live('keyUp',function() {
            $('#Text1').val( $(this).val() );
        });
        $('#cardvalidatemes2').live('change',function() {
            $('#Text1').val( $(this).val() );      
        });
        // Ano 2
        $('#cardvalidatemano2').live('keyUp',function() {
            $('#Text2').val( $(this).val() );
        });
        $('#cardvalidatemano2').live('change',function() {
            $('#Text2').val( $(this).val() );      
        });
        // codigo do cartao 2
        $('#cardcode2').live('keyUp',function() {
            $('#paymentCard2Code').val( $(this).val() );
        });
        $('#cardcode2').live('change',function() {
            $('#paymentCard2Code').val( $(this).val() );      
        });
        // codigo do cartao ilegivel 1
        $('#ilegivel2').live('click',function() {
            $('#paymentCard2IsUnreadable').trigger('click');
        });
        // valor 1
        $('#totalvalue2').live('keyUp',function() {
            $('#paymentCard2Value').val( $(this).val() );
            $('#paymentCard2Value').trigger('change');
            $('#paymentCard2Value').trigger('keyup');
            $('#paymentCard2Value').trigger('keydown');
        });
        $('#totalvalue2').live('change',function() {
            $('#paymentCard2Value').val( $(this).val() );  
            $('#paymentCard2Value').trigger('change');
            $('#paymentCard2Value').trigger('keyup');
            $('#paymentCard2Value').trigger('keydown');
        });
        // parcelamento 1
        $('#paymenttimes2').live('keyUp',function() {
            $('#paymentCard2Installments').val( $(this).val() );
        });
        $('#paymenttimes2').live('change',function() {
            $('#paymentCard2Installments').val( $(this).val() );      
        });
        // Valor Total 2
        $('#totalvalue2').live('keyUp',function() {
            $('#paymentCard2Value').val( $(this).val() );
        });
        $('#totalvalue2').live('change',function() {
            $('#paymentCard2Value').val( $(this).val() );      
        });
        
        //####################################################################
        
        

    }
    
    //$('#productList tr.itemGift td.productName').html( $('#productList tr.itemGift td.productName').html().replace("Embalagem para presente","" ) );
    
	Cufon.replace('#heading #checkout-navigation ul li a .name', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('#checkoutData h2', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('#main #steps legend', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('#main #cart table h3', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('#main #cart table thead', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('#main #summary h2', {
        fontFamily: 'Proxima Nova Rg'
    });
    Cufon.replace('#main #first-steps h3', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('#summary li.total .title', {
        fontFamily: 'Proxima Nova Rg'
    });	
	Cufon.replace('#footer .wrapper a', {
        fontFamily: 'Proxima Nova Rg'
    });
	
	Cufon.replace('#orderperfect h1', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('#orderperfect #orderContent #orderNumber p', {
        fontFamily: 'Proxima Nova Rg'
    });
	
	//Numeros
	Cufon.replace('#heading #checkout-navigation ul li a .number', {
        fontFamily: 'ITC Tiffany Std'
    });
	

    $('#cartnavigator li a:contains("Comprar Mais Produto")').css({'padding-right' : '28px' }).html("Comprar Mais Produtos ");
    
	$('#orderContent').addClass("clearfix");
	
	$('#main #steps #Form .submit, #main #steps a, #paymentTypeOptions li').click(function () {

		$('#main #checkoutData h2 a').css({ 'display' : 'block' });
		
		Cufon.replace('#steps #boxPayment legend, #steps #boxPayment h4', {
			fontFamily: 'Proxima Nova Rg'
		});
	
	});
	
	
    $('#cleancart').live('click',function() {
            
            while (  $('.cartItemRemove').size() > 0  ) {
                $('.cartItemRemove').trigger('click');
            }
    });
	
    //#################################################################################
    
    
    $('td.quantity input').each(function () {
        $(this).before('<a class="inputup" href="javascript:void(0)">Up</a>');
        $(this).after('<a class="inputdown" href="javascript:void(0)">Down</a>');
        
	});
    
    $('td.quantity input').each(function () {
        $(this).before('<a class="inputup" href="javascript:void(0)">Up</a>');
        $(this).after('<a class="inputdown" href="javascript:void(0)">Down</a>');
        
	});
    
    
    
    $('tr.itemGift td.productName').each(function () {
        $(this).prepend('<span class="giftlabel">Digite aqui sua mensagem para presente</span>');
    });
    
	
	$('#main #cart table .quantity input:text').change(function() {
        //$('tr.itemGift .quantityPrice').html('R$ 0,00');
		updatecart();
		var row = $(this).parent().parent().parent();
		var regularprice = $(this).prev().val() * parseFloat( $(row).find('.newproductPrice').html().replace("R$","").replace(" ","").replace(".","").replace(",",".") );
		$(row).find('.quantityPrice span').html( "R$ " + float2moeda( regularprice.toFixed(2) ) );
	});
	
	

	// Increase button.
	$('.inputup').live('click',function () {
        
        //$('tr.itemGift .quantityPrice').html('R$ 0,00');
        
		if( parseInt($(this).next().val()) < 99 ) {
			$(this).next().val( parseInt($(this).next().val()) + 1 ); 
			$(this).next().trigger('change');
			$(this).next().trigger('keyup');
			$(this).next().trigger('keydown');
            updatecart();
			var row = $(this).parent().parent().parent();
			var regularprice = $(this).next().val() * parseFloat( $(row).find('.newproductPrice').html().replace("R$","").replace(" ","").replace(".","").replace(",",".") );
			$(row).find('.quantityPrice span').html( "R$ " + float2moeda( regularprice.toFixed(2) ) );
		}
	});
	// Decrease Button.
	$('.inputdown').live('click',function () {
        //$('tr.itemGift .quantityPrice').html('R$ 0,00');
		if( parseInt($(this).prev().val()) > 1 ) {
			$(this).prev().val( parseInt($(this).prev().val()) - 1 ); 
            $(this).prev().trigger('change');
			$(this).prev().trigger('keyup');
			$(this).prev().trigger('keydown');
			updatecart();
			var row = $(this).parent().parent().parent();
			var regularprice = $(this).prev().val() * parseFloat( $(row).find('.newproductPrice').html().replace("R$","").replace(" ","").replace(".","").replace(",",".") );
			$(row).find('.quantityPrice span').html( "R$ " + float2moeda( regularprice.toFixed(2) ) );
		}

	});
    
	
	$("#cartShipping fieldset legend").text("Digite seu CEP");
	$("#cartShipping fieldset p:first").css({
		"background" : "url('/Control/ArquivoExibir.aspx?NomeArquivo=icon_index_1.gif') no-repeat left center",
		"padding" : "10px 0 10px 40px"
	});
	//$("#cartShipping fieldset p:first input:text").val("");
	$("#cartShipping fieldset p:first input:text").attr("maxlength", 8);
	
    // Alterando labels dos endereços
    $('#boxShipMyAddresses label').html('Em qual endereço devemos entregar?');
    
	// Titulo da seção de mensagem para presente
	
	$("div.giftMessage").each(function(){
		$(this).find("textarea").before("<p>Escreva um cartão e clique para salvar</p>");
	});
	
	
    //toltop add presente
    $('.lnkGiftMessage a,#productList .addGift').live('mouseenter',function() {
    
        $(this).append('<img class="tolltipgift" src="/Control/ArquivoExibir.aspx?NomeArquivo=img_gift_tolltip.png" />')
    
    });
    
    $('.lnkGiftMessage a,#productList .addGift').live('mouseleave',function() {
    
        $(this).find('.tolltipgift').remove();
    });
    
    /*//remove presente
    $('#productList .giftMessageCancel').live('mouseenter',function() {
    
        $(this).append('<img class="tolltipcancel" src="/Control/ArquivoExibir.aspx?NomeArquivo=tooltip_cancelar.png" />')
    
    });
    
    $('#productList .giftMessageCancel').live('mouseleave',function() {
    
        $(this).find('.tolltipcancel').remove();
        
    });
    
    //save presente
    $('#productList .giftMessageSave').live('mouseenter',function() {
    
        $(this).append('<img class="tolltipsave" src="/Control/ArquivoExibir.aspx?NomeArquivo=tooltip_salvarcartao.png" />')
    
    });
    
    $('#productList .giftMessageSave').live('mouseleave',function() {
    
        $(this).find('.tolltipsave').remove();
        
    });*/
    
    // Troca o botão "Clique para informar o endereço" por um select com os endereços disponiveis
		
	//$('#shipMyAddresses').jQSelect({ rotulo : "Selecionar Endere&ccedil;o" });
		
	if($("body").hasClass("checkout") && $("#addadressbutton").length > 0){
        // firstship
		//$("#registeraddress #registerform #boxShipMyAddresses").prependTo($("#addadressbutton").parent());
		$("#address .jQcustomselect").remove();
        $('#shipMyAddresses').jQSelect({ rotulo : "Selecionar Endere&ccedil;o" });
        $('#shipMyAddresses').parent().find('.jQcustomselect').prependTo($("#addadressbutton").parent());
        
		$("#registerform #button0").clone().appendTo($(".warpit")).css("display", "none");
		
		
		
        $('#shipMyAddresses').live('change', function(){
			
			if($(this).attr("value") == 0){
				$("#registeraddress").css("display", "block");
				$("#addresslabels #button0").css("display", "none");
				$("#addresslabels > p").remove();
				$("#paymentoptions").css("display", "none");
				$('html, body').animate({
					scrollTop: $("#registeraddress").offset().top
            }, 800);
            $('#idfreteui').remove();
            
			}else{
				if($(this).attr("value") != 0 && $("#registeraddress").is(":visible")){
					$("#registeraddress").css("display", "none");
				}
				//$("#addresslabels #button0").css("display", "block");
			}
            
            $('#cepreflect').val( $('#shipCep').val()  );
            
		});
	}
	
	
	
    $(document).ajaxComplete(function(event,request, settings){

            
           // $('.giftMessage textarea').placeholder(); 
       
    
       // $('#productList tr.itemGift td.productName').html( $('#productList tr.itemGift td.productName').html().replace("Embalagem para presente","" ) );
    
    
    
        Cufon.replace('#main #cart table h3', {
            fontFamily: 'Proxima Nova Rg'
        });       
  
        
        var intervalo = window.setTimeout(function() {
        
        
            // parcelamento 
            //Quando o ajax ficar completo se nescessário delete os items do form e coloque novamente.
            
            
             //Remover esse comentário
            $('#formcard .paymenttimes .jQcustomselect').remove();
            
            // UL do parcelamento 1
            $('#paymentCard1Installments').jQSelect({ rotulo : "Parcelas" });
            $('#paymentCard1Installments').prev().appendTo('#formcard .paymenttimes');
                    
            //UL do parcelamento 2
            $('#secondcardcontainer .paymenttimes .jQcustomselect').remove();
            
            $('#paymentCard2Installments').jQSelect({ rotulo : "Parcelas" });
            $('#paymentCard2Installments').prev().appendTo('#secondcardcontainer .paymenttimes');
            
            
            //Fim Parcelamento
        
        
           // $('#productList tr.itemGift td.productName').html( $('#productList tr.itemGift td.productName').html().replace("Embalagem para presente","" ) );
            if( $('.giftlabel').size() == 0 ){ 
            
                $('tr.itemGift td.productName').each(function () {
                    $(this).prepend('<span class="giftlabel">Digite aqui sua mensagem para presente</span>');
                });

            }
            
            if( $('.inputup').size() == 0 ){ 
                //$('tr.itemGift .quantityPrice').html('R$ 0,00');
                $('td.quantity input').each(function () {
                $(this).before('<a class="inputup" href="javascript:void(0)">Up</a>');
                $(this).after('<a class="inputdown" href="javascript:void(0)">Down</a>');
                });
              
            }
            
            Cufon.replace('#productList tr:not(".itemGift") .productName', {
                fontFamily: 'Proxima Nova Rg'
            });   
        
            if ( $('#cartMessages li:contains("falta de estoque")').size() > 0 ){
                
                $('th.quantity .outstock').remove();
                $('th.quantity').append('<div style="position:relative"><img class="outstock" src="/Control/ArquivoExibir.aspx?NomeArquivo=tooltip-erro-estoque.png" alt="Sem estoque" /></div>');
            
            } else {
            
                $('th.quantity .outstock').remove();
            
            } 
        
        }, 500);
        
        Cufon.replace('#productList tr:not(".itemGift") .productName', {
            fontFamily: 'Proxima Nova Rg'
        });   
        
        $('')
        
    });    
        
        $(document).ajaxError(function(event,request, settings){
    
    
       Cufon.replace('#productList tr:not(".itemGift") .productName', {
            fontFamily: 'Proxima Nova Rg'
        });   
        
            
           // $('.giftMessage textarea').placeholder(); 
       
    
       // $('#productList tr.itemGift td.productName').html( $('#productList tr.itemGift td.productName').html().replace("Embalagem para presente","" ) );
    
    
    
        Cufon.replace('#main #cart table h3', {
            fontFamily: 'Proxima Nova Rg'
        });       
    
        
        
        
        var intervalo = window.setTimeout(function() {
        
            //$('#productList tr.itemGift td.productName').html( $('#productList tr.itemGift td.productName').html().replace("Embalagem para presente","" ) );
        
            if( $('.inputup').size() == 0 ){ 
                //$('tr.itemGift .quantityPrice').html('R$ 0,00');
                $('td.quantity input').each(function () {
                $(this).before('<a class="inputup" href="javascript:void(0)">Up</a>');
                $(this).after('<a class="inputdown" href="javascript:void(0)">Down</a>');
                });
              
            }
        
            Cufon.replace('#productList tr:not(".itemGift") .productName', {
                fontFamily: 'Proxima Nova Rg'
            });   
        
        
        }, 600);
        
        
    });    
	
	$('#cartShippingChoice').jQSelect({ rotulo : "Selecione o tipo de frete" });
    $('#cartShipping legend').after('<legend>Tipo de Entrega</legend>');
	$('.cartExtras fieldset p:eq(0)').css({ 'clear':'both' });
    $('.cartExtras fieldset p:eq(1)').css({ 'background-image' : 'url("/Control/ArquivoExibir.aspx?NomeArquivo=icon_index_2.png")' , 'background-repeat' : ' no-repeat ' , 'background-position' : ' 2px 9px' , 'padding-left' : '40px' });
    $('.cartExtras fieldset p:eq(1)').addClass('no-repeat');
    
    $("#cartCep").keyup(function(){
		//if($(this).val().replace('_', '').length == 9){
			$(this).parent().next().find('.jQcustomselect').remove();
			$('#cartShippingChoice').jQSelect({ rotulo : "Selecione o tipo de frete" });
	   //}
	});
 
    //selecionar endereço
    
    $('#address .jQcustomselect .jQSelect li').live('click',function() {
                
            $('#addresslabels p:has(label)').remove();
            $('#buttoneditaddress').remove();
                
            $('#addresslabels p:has(label)').remove();
            $('#Info p:not(".notification")').clone().appendTo('#addresslabels');
            $('#addresslabels .padding').removeClass();

            $('#addresslabels .warpit').appendTo('#addresslabels');
        
            $('#idfreteui').remove();
            
            $("#addresslabels #button0").hide();
                
            var selectdelay = window.setTimeout(function() {
            
                $('.warpit').prepend(' \
                    <div id="idfreteui"> \
                        <ul></ul> \
                    </div>');
                
                $('li.radio:has(label[for=shipChoice0])').clone().appendTo('#idfreteui ul');
                $('li.radio:has(label[for=shipChoice1])').clone().appendTo('#idfreteui ul');
                $('#idfreteui ul li input').remove();
                //$('#idfreteui ul li label').prepend('<input type="radio" name="shipChoicereflect" >');
                
                if( $('li.radio:has("label[for=shipChoice1]"):last').find('input:checked').size() > 0 ){
                    $('#idfreteui li label:last').addClass('active');
                    $("#addresslabels #button0").show();
                }else if ( $('li.radio:has("label[for=shipChoice0]"):last').find('input:checked').size() > 0 ) {
                    $('#idfreteui li label:first').addClass('active');
                    $("#addresslabels #button0").show();
                }
                
            },400);
        
            $('#idfreteui ul li label').live('click',function() {
                
                $(this).parent().trigger('click');
            
            });
            
            $('#paymentoptions,#paypalpayment,#debitopayment,#credictcardform').hide();
            
            var delaytoconfig = window.setTimeout(function(){
        
                $('#address').css({ 'height' : 'auto' });
                $("#informations").css({ 'height' : 'auto' });
            
                if (  $("#address").height() > $("#informations").height() ) {
                    $("#informations").css("height", $("#address").height());
                }else{
                    $("#address").css("height",  $("#informations").height());
                }
            
            },800);
    });
    
    $('#credictcardform .cardvalidate .jQcustomselect li').live('click',function() {
    
        $(this).parent().parent().parent().find('.warning').remove();
    
    });
    
    
    $('#idfreteui ul li label').live('click',function() {
     
        $('#idfreteui ul li label').removeClass('active');
        $(this).addClass('active');
        $("#addresslabels #button0").css("display", "block");
        
        var delaytoconfig = window.setTimeout(function(){
        
                $('#address').css({ 'height' : 'auto' });
                $("#informations").css({ 'height' : 'auto' });
            
                if (  $("#address").height() > $("#informations").height() ) {
                    $("#informations").css("height", $("#address").height());
                }else{
                    $("#address").css("height",  $("#informations").height());
                }
            
        },500);
        

    });
    
    
    // Selecionando a primeira ul.
    $('#address #boxShipMyAddresses .jQcustomselect .jQSelect li:eq(1)').click();
    
    /*
    var formvalid = true;
            $('#registerform .required input').each(function () {
                if ( $(this).val() == "" ){
                    
                    formvalid = false;
                }
            });

            
            if ( formvalid == false ) {

                $("#registeraddress").show();
                 $('html, body').animate({
                    scrollTop: $("#registeraddress").offset().top - 10
                }, 800);
            }*/
    
    $('#cartShipping fieldset').after('<p class="infocheckout">(*) Entrega Expressa somente para S&atilde;o Paulo Capital: todos pedidos confirmados at&eacute; &agrave;s 13hs ser&atilde;o entregues at&eacute; &agrave;s 20hs do mesmo dia.</p>');
    $('#infocheckout').width(485);
    
    $('#cepreflect').val( $('#shipCep').val()  );
    
    //order completed
    if ( $('body').is('.orderCompleted') ) {
    
        $('#cart').appendTo('#main');
        $('#cart h2').remove();
        $('.continueNavegando').appendTo('#main');
    
    }
    
    
    $('#cartShipping .jQcustomselect .jQSelect li').live('click',function() {
    
        $('#submitCartCep').submit();
    
    });
    
    $('#address .jQcustomselect .jqselectlabel').html("Selecione uma op&ccedil;&atilde;o");
    
    
    var googleAnalyticsTrackers = setTimeout(function(){
	
		/* 
		*	INÃCIO DO CÓDIGO DE SOCIAL TAG - FBIZ
		*	************NÃO APAGUE***************
		*/
		setTimeout(function(){var a=document.createElement("script");
		var b=document.getElementsByTagName('script')[0];
		a.src=document.location.protocol+"//dnn506yrbagrg.cloudfront.net/pages/scripts/0010/4256.js";
		a.async=true;a.type="text/javascript";b.parentNode.insertBefore(a,b)}, 1);
		/* TÉRMINO DO CÓDIGO DE SOCIAL TAG - FBIZ */
        
        // Seleção de Endereço
		$('#addresslabels .jQcustomselect .jQSelect li').bind('click',function(){
            _gaq.push(['_trackPageview', 'checkout/endereco']);
        }); 
        // Seleção da forma de pagamento
        $('#paymentoptions li label').bind('click',function(){
            _gaq.push(['_trackPageview', 'checkout/pagamento']);
        });   
        
        
        
	}, 3000);
    
    
    if( $('body').is('.shoppingCart') ){
    
        if ( $('#emptyCart:visible').size() > 0 ){
        
            $('#cartnavigator ul li:lt(2)').hide();        
        
        }
    
        $(document).ajaxComplete(function(e, xhr, settings) {
             
            if ( $('#emptyCart:visible').size() > 0 ){
                $('#cartnavigator ul li:lt(2)').hide();        
            }else{
               $('#cartnavigator ul li').show();
            }
            
            window.setTimeout(function(){
            
                PercorrerCarrinho();
            
            },1000);
            
        });
        
        
        // ################################
        if ( $(window).height() - $('#modal').height() > 0 ){
            $('#modal').css({ 'margin-left' : "-" + ( $('#modal').width() / 2 ) + "px" , top : ( $(window).height() - $('#modal').height() ) / 2 });
        }else{
            $('#modal').css({ 'margin-left' : "-" + ( $('#modal').width() / 2 ) + "px" , top : '10px' });
        }
        
        $('#overlay-bg, #closebutton').click(function(){
        
            $('#modal').fadeOut();
            $('#overlay-bg').fadeOut('slow');
        
        });
        
        $('.view-modal').live('click',function(){
            
            if ( $(window).height() - $('#modal').height() > 0 ){
                $('#modal').css({ 'margin-left' : "-" + ( $('#modal').width() / 2 ) + "px" , top : ( $(window).height() - $('#modal').height() ) / 2 });
            }else{
                $('#modal').css({ 'margin-left' : "-" + ( $('#modal').width() / 2 ) + "px" , top : '10px' });
            }
            
            $('#overlay-bg').fadeIn();
            $('#modal').fadeIn('slow');
            
        });
        // ################################
        
    }
    
});	


$(document).ready(function() {

    $("#cepreflect").mask("99999999");  

});


function PercorrerCarrinho() {
    
     $('tr.itemGift').each(function() {
                console.log($(this).find('.view-modal').size());
                if ( $(this).find('.view-modal').size() == 0 ){
                
                    $(this).find('.productName').append('<span class="view-modal" href="javascript:void(0)">Embalagens</span>');
                
                }
            
            });

    
}

function updatecart() {
	//$('tr.itemGift .quantityPrice').html('R$ 0,00');
	var total = 0;
	
	$("#main #cart table tr:has('.quantity input')").each(function () {
		total += parseFloat( $(this).find('.quantity input').val() ) * parseFloat( $(this).find('.newproductPrice').html().replace("R$","").replace(" ","").replace(".","").replace(",",".") ) ;
	});
	
	$('#main #summary .subtotal .number').html( float2moeda( total ) );
	
	if( $("#main #summary .ship .number:contains('tis')") ) {
		$('#main #summary .total .description').html( "R$ " + float2moeda( total));
		$('#totals #totalsTotal .description').html( "R$ " + float2moeda( total));
	}else {
		$('#main #summary .total .description').html( "R$ " + float2moeda( parseFloat( $("#main #summary .ship .number").html().replace("R$","").replace(" ","") ) + total ).toFixed(2) );
		$('#totals #totalsTotal .description').html( "R$ " + float2moeda( parseFloat( $("#main #summary .ship .number").html().replace("R$","").replace(" ","") ) + total ).toFixed(2) );
	}
    
}

function float2moeda(num) {

   x = 0;

   if(num<0) {
      num = Math.abs(num);
      x = 1;
   }
   if(isNaN(num)) num = "0";
      cents = Math.floor((num*100+0.5)%100);

   num = Math.floor((num*100+0.5)/100).toString();

   if(cents < 10) cents = "0" + cents;
      for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
         num = num.substring(0,num.length-(4*i+3))+'.'
               +num.substring(num.length-(4*i+3));
               ret = num + ',' + cents;
               if (x == 1) ret = ' - ' + ret;return ret;

}

//##################################################################
(function($) {
$.fn.placeholder = function(options) {
	var defaults = {css_class: "placeholder"};
	var options = $.extend(defaults, options);  
	this.each(function() {
		if ($(this).attr('placeholder') !== undefined) {
			var phvalue = $(this).attr("placeholder");
			var currvalue = $(this).attr("value");
			if (phvalue == currvalue) {
				$(this).addClass(options.css_class);
			}
			if (currvalue == "") {
				$(this).addClass(options.css_class);
				$(this).val(phvalue);
			}
			$(this).focusin(function(){
				var ph = $(this).attr("placeholder");
				if (ph == $(this).val()) {
					$(this).val("").removeClass(options.css_class);
				}
			});
			
			$(this).focusout(function(){
				var ph = $(this).attr("placeholder");
				if ($(this).val() == "") {
					$(this).val(ph).addClass(options.css_class);
				}
			});
		}
	});
	return this;
	};
})(jQuery);

/*
	Masked Input plugin for jQuery
	Copyright (c) 2007-2011 Josh Bush (digitalbush.com)
	Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license) 
	Version: 1.3
*/
(function(a){var b=(a.browser.msie?"paste":"input")+".mask",c=window.orientation!=undefined;a.mask={definitions:{9:"[0-9]",a:"[A-Za-z]","*":"[A-Za-z0-9]"},dataName:"rawMaskFn"},a.fn.extend({caret:function(a,b){if(this.length!=0){if(typeof a=="number"){b=typeof b=="number"?b:a;return this.each(function(){if(this.setSelectionRange)this.setSelectionRange(a,b);else if(this.createTextRange){var c=this.createTextRange();c.collapse(!0),c.moveEnd("character",b),c.moveStart("character",a),c.select()}})}if(this[0].setSelectionRange)a=this[0].selectionStart,b=this[0].selectionEnd;else if(document.selection&&document.selection.createRange){var c=document.selection.createRange();a=0-c.duplicate().moveStart("character",-1e5),b=a+c.text.length}return{begin:a,end:b}}},unmask:function(){return this.trigger("unmask")},mask:function(d,e){if(!d&&this.length>0){var f=a(this[0]);return f.data(a.mask.dataName)()}e=a.extend({placeholder:"_",completed:null},e);var g=a.mask.definitions,h=[],i=d.length,j=null,k=d.length;a.each(d.split(""),function(a,b){b=="?"?(k--,i=a):g[b]?(h.push(new RegExp(g[b])),j==null&&(j=h.length-1)):h.push(null)});return this.trigger("unmask").each(function(){function v(a){var b=f.val(),c=-1;for(var d=0,g=0;d<k;d++)if(h[d]){l[d]=e.placeholder;while(g++<b.length){var m=b.charAt(g-1);if(h[d].test(m)){l[d]=m,c=d;break}}if(g>b.length)break}else l[d]==b.charAt(g)&&d!=i&&(g++,c=d);if(!a&&c+1<i)f.val(""),t(0,k);else if(a||c+1>=i)u(),a||f.val(f.val().substring(0,c+1));return i?d:j}function u(){return f.val(l.join("")).val()}function t(a,b){for(var c=a;c<b&&c<k;c++)h[c]&&(l[c]=e.placeholder)}function s(a){var b=a.which,c=f.caret();if(a.ctrlKey||a.altKey||a.metaKey||b<32)return!0;if(b){c.end-c.begin!=0&&(t(c.begin,c.end),p(c.begin,c.end-1));var d=n(c.begin-1);if(d<k){var g=String.fromCharCode(b);if(h[d].test(g)){q(d),l[d]=g,u();var i=n(d);f.caret(i),e.completed&&i>=k&&e.completed.call(f)}}return!1}}function r(a){var b=a.which;if(b==8||b==46||c&&b==127){var d=f.caret(),e=d.begin,g=d.end;g-e==0&&(e=b!=46?o(e):g=n(e-1),g=b==46?n(g):g),t(e,g),p(e,g-1);return!1}if(b==27){f.val(m),f.caret(0,v());return!1}}function q(a){for(var b=a,c=e.placeholder;b<k;b++)if(h[b]){var d=n(b),f=l[b];l[b]=c;if(d<k&&h[d].test(f))c=f;else break}}function p(a,b){if(!(a<0)){for(var c=a,d=n(b);c<k;c++)if(h[c]){if(d<k&&h[c].test(l[d]))l[c]=l[d],l[d]=e.placeholder;else break;d=n(d)}u(),f.caret(Math.max(j,a))}}function o(a){while(--a>=0&&!h[a]);return a}function n(a){while(++a<=k&&!h[a]);return a}var f=a(this),l=a.map(d.split(""),function(a,b){if(a!="?")return g[a]?e.placeholder:a}),m=f.val();f.data(a.mask.dataName,function(){return a.map(l,function(a,b){return h[b]&&a!=e.placeholder?a:null}).join("")}),f.attr("readonly")||f.one("unmask",function(){f.unbind(".mask").removeData(a.mask.dataName)}).bind("focus.mask",function(){m=f.val();var b=v();u();var c=function(){b==d.length?f.caret(0,b):f.caret(b)};(a.browser.msie?c:function(){setTimeout(c,0)})()}).bind("blur.mask",function(){v(),f.val()!=m&&f.change()}).bind("keydown.mask",r).bind("keypress.mask",s).bind(b,function(){setTimeout(function(){f.caret(v(!0))},0)}),v()})}})})(jQuery)
